package com.ling.module1sbbyyds.server;

import com.ling.module1sbbyyds.config.MyEndpointConfig;
import com.ling.module1sbbyyds.service.news.chat.ChatRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


/**
 * @Description: 聊天室连接服务
 * @author: ling
 * @date: 2023年02月12日
 */
@Slf4j
@Component
@ServerEndpoint(value = "/imserver/{token}", configurator = MyEndpointConfig.class)
public class ChatRoomServer {

    @Autowired
    private ChatRoomService chatRoomService;


    /**
     * 用户建立连接
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        chatRoomService.clientOpenConnection(token, session);
    }

    /**
     * 接收客户端消息
     *
     * @param message 客户端发送过来的消息
     *                格式：{
     *                "token":"eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTU5MjEzMTYsInVzZXJJZCI6NywiaWF0IjoxNjU1MDMyMjgzfQ.7yKn8a9-z_tQH6LRroGj2vqBbNf-bAp5achlx6IdQhY",
     *                "sendUserId":"1",
     *                "toUserId":"2",
     *                "message":"你好，用户2！"
     *                }
     */
    @OnMessage
    public void onMessage(String message) {
        chatRoomService.clientChatOperation(message);
    }


    /**
     * 连接关闭
     *
     * @param session 会话
     */
    @OnClose
    public void onClose(Session session) {
        chatRoomService.clientSessionClose(session);
    }
}
